﻿//---------------------------------------------------------------------
// Copyright (c) 2007 Digerati Technologies, LLC.  All Rights Reserved.
//
// Release under the Microsoft Public License (Ms-PL).
//---------------------------------------------------------------------

using System.Net;

namespace DigeratiTech.NDiagnostics
{
    /// <summary>
    /// This <see cref="DiagnosticTask"/> verifies that the specified file exists.
    /// </summary>
    public class UrlTask : DiagnosticTask
    {
        #region Properties...

        /// <summary>
        /// Gets or sets the URL to be validated.
        /// </summary>
        /// <value>The URL to be validated.</value>
        /// <remarks>The specified URL must be accessible for this task to succeed.</remarks>
        public string Url { get; set; }

        #endregion

        #region Constructors...

        /// <summary>
        /// Initializes a new instance of the <see cref="UrlTask"/> class.
        /// </summary>
        /// <param name="group">The <see cref="TaskGroup"/> this task belongs to.</param>
        /// <param name="name">The task name.</param>
        /// <param name="url">The URL to be validated.</param>
        public UrlTask(TaskGroup group, string name, string url)
        {
            taskGroup = group;
            Name = name;
            Url = url;
            Status = TaskStatus.NotRun;
        }

        #endregion

        #region Methods...

        /// <summary>
        /// Executes the task.
        /// </summary>
        /// <returns>
        /// 	<c>true</c> if the task is successful; otherwise, <c>false</c>.
        /// </returns>
        public override bool Execute()
        {
            Status = TaskStatus.Completed;
            Message = string.Empty;

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);
            
            // Set the credentials to the current user account
            request.Credentials = System.Net.CredentialCache.DefaultCredentials;

            request.Method = "GET";

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    // Do nothing; we're only testing to see if we can get the response
                }
            }
            catch (WebException ex)
            {
                Status = TaskStatus.Error;
                Message += ((Message.Length > 0) ? "\n" : "") + ex.Message;
            }

            return (Message.Length == 0);
        }

        #endregion
    }
}
